<template>
  <div class="image-management">
    <h2>图片管理</h2>
    
    <div class="action-bar">
      <UploadImage @upload-success="fetchImages" />
    </div>
    
    <el-table :data="images" style="width: 100%">
      <el-table-column prop="filename" label="文件名" width="180" />
      <el-table-column label="预览" width="120">
        <template #default="{ row }">
          <el-image 
            :src="row.url" 
            :preview-src-list="[row.url]"
            fit="cover"
            style="width: 100px; height: 60px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="url" label="URL" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button 
            type="danger" 
            size="small" 
            @click="deleteImage(row.filename)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import UploadImage from '@/components/UploadImage.vue'
import axios from '@/utils/request'

const images = ref([])

const fetchImages = async () => {
  try {
    const res = await axios.get('/api/images')
    images.value = res.data
  } catch (error) {
    ElMessage.error('获取图片列表失败')
  }
}

const deleteImage = (filename) => {
  ElMessageBox.confirm('确定删除这张图片吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/images/${filename}`)
      ElMessage.success('删除成功')
      fetchImages()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchImages()
})
</script>

<style scoped>
.image-management {
  padding: 20px;
}
.action-bar {
  margin-bottom: 20px;
}
</style>